package com.hns.can.master.service;

import com.hns.can.master.entity.BaseQuickLinkEntity;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.DateTool;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilConfig;
import com.hns.tool.pub.UtilString;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;

/**
 * 云总线快捷链接控制类
 *
 * @author jeff
 * @email 835264047@qq.com
 */
@Service
public class BaseQuickLinkService extends CommonService {

    /**
     * 得到云总线快捷链接的信息
     *
     * @return
     */
    public List<BaseQuickLinkEntity> getQuickLinks() {

        List<BaseQuickLinkEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseQuickLink.getQuickLinks", null), BaseQuickLinkEntity.class);

        return list;
    }

    /**
     * 保存云总线快捷链接的信息
     *
     * @param names
     * @param urls
     * @param sequences
     */
    @Transactional
    public void saveQuickLinks(String[] names, String[] logos, String[] urls, BigDecimal[] sequences) {

        //删除原有的库表
        this.sqlMapDao.delete("baseQuickLink.deleteQuickLinks");

        //保存现在的信息
        if (PubUtil.isNotEmpty(names)) {
            BaseQuickLinkEntity entity = null;
            for (int i = 0; i < names.length; i++) {
                String name = names[i];
                String logo = logos[i];
                String url = urls[i];
                BigDecimal sequence = sequences[i];

                entity = new BaseQuickLinkEntity();

                entity.setId(UtilString.getUUID());
                entity.setLogo(logo);
                entity.setName(name);
                entity.setUrl(url);
                entity.setSequence(sequence);

                this.commonEntityDao.save(entity);
            }
        }
    }

    public String fileUpload(
            @RequestParam MultipartFile[] myfiles, String uploadPath,
            HttpServletRequest request, HttpServletResponse response) throws IOException {
        //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
        //这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建
//        String realPath = request.getSession().getServletContext().getRealPath("/") + uploadPath;
        String realPath = UtilConfig.getString("upload_file_base_path") + uploadPath;//自定义图片保存路径

        //上传文件的原名(即上传前的文件名字)
        String originalFilename = null;
        //保存的文件名
        String saveFileName = "";

        //设置响应给前台内容的数据格式
        response.setContentType("text/plain; charset=UTF-8");
        //设置响应给前台内容的PrintWriter对象
        PrintWriter out = response.getWriter();
        //上传文件的原名(即上传前的文件名字)
        //如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
        //如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且要指定@RequestParam注解
        //上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件
        for (MultipartFile myfile : myfiles) {

            System.out.println(URLDecoder.decode(myfile.getOriginalFilename(), "UTF-8"));

            if (myfile.isEmpty()) {
                throw new BusinessException(MsgType.WARN.getFlag(), "请选择文件后上传");
            } else {
                //originalFilename = URLDecoder.decode(myfile.getOriginalFilename(), "UTF-8");
                originalFilename = new String(myfile.getOriginalFilename().getBytes("ISO-8859-1"), "utf-8");
                saveFileName = DateTool.getCurrentSysDate("yyyyMMddHHmmss") + originalFilename.substring(originalFilename.lastIndexOf("."));

                try {
                    //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
                    //此处也可以使用Spring提供的MultipartFile.transferTo(File dest)方法实现文件的上传
                    FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, saveFileName));
                } catch (IOException e) {
                    System.out.println("文件[" + originalFilename + "]上传失败,堆栈轨迹如下");
                    e.printStackTrace();

                    out.print("1文件上传失败，请重试！！");
                    out.flush();
                    return null;
                }
            }
        }
        out.print("0" + uploadPath + "\\" + saveFileName);
        out.flush();

        return null;
    }

    public void readImage(String uploadPath, HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String imagePath = request.getSession().getServletContext().getRealPath("/") + uploadPath;
        String imagePath = UtilConfig.getString("upload_file_base_path") + uploadPath;//自定义图片保存路径

        imagePath = new String(imagePath.getBytes("ISO-8859-1"), "utf-8");
        try {
            File file = new File(imagePath);
            if (file.exists()) {
                DataOutputStream temps = new DataOutputStream(response.getOutputStream());
                DataInputStream in = new DataInputStream(new FileInputStream(imagePath));
                byte[] b = new byte[2048];
                while ((in.read(b)) != -1) {
                    temps.write(b);
                    temps.flush();
                }
                in.close();
                temps.close();
            }
        } catch (Exception e) {
            System.out.println("读取图片错误");
            e.printStackTrace();
        }
    }


}
